package com.example.mall.order.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 设置RabbitMQ发送端的回调
 */
@Slf4j
@Component
public class RabbitCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                log.info("correlationData = {}", correlationData);
                log.info("b = {}", b);
                log.info("s = {}", s);
            }
        });

        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                byte[] messageBodyByte = returnedMessage.getMessage().getBody();
                log.info("returnedMessage = {}", returnedMessage);
                log.info("returnedMessage.getMessage().getBody() = {}", new String(messageBodyByte, 0, messageBodyByte.length));
            }
        });
    }
}
